# !/usr/bin/env python3
# -*- coding: utf-8 -*-
###----------------------------------------------------1、文件说明----------------------------------------------------###
'''
* 说明：操作docx的库的学习笔记
* 时间：2021-1-18
* 文件：
* 作者：whg
* 备注：
'''
###----------------------------------------------------2、库导入----------------------------------------------------###
import cv2
from PIL import Image
import numpy as np
import wfile
import matplotlib.pyplot as plt
import wx
import os
###----------------------------------------------------3、参数配置----------------------------------------------------###
###----------------------------------------------------4、主体程序----------------------------------------------------###

class WImg(object):
    '''
    处理图片
    '''
    def __init__(self, photoname):
        self.photoname = photoname
        img = Image.open(photoname).convert("RGBA")
        self.img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGBA2BGRA)
    def GetCVData(self, num=3):
        return self.img
    def GetPILData(self):
        return self.CVToPIL(self.img)
    def GetWXData(self):
        return self.CVToWX(self.img)
    def ShowChannel(self):
        print(self.img.shape)
        simg = cv2.split(self.img) # 分割图片
        print(simg[0].shape)
        color = ["B", "G", "R", "A"]
        for i in range(len(simg)):
            plt.title(color[i] + ' - Channel')
            plt.axis('off')
            plt.imshow(simg[i], cmap='Greys_r')
            plt.show()
    def PltShow(self, img):
        plt.imshow(img)
        # 不显示坐标轴
        plt.axis('off')
        plt.savefig('aaa.jpg', bbox_inches="tight", pad_inches=0.0)
        plt.show()

    #----------Opencv----------#
    def CVOpen(self, name):
        img = cv2.imread(name, cv2.IMREAD_UNCHANGED) # 读取图片本身维度 png 4维  黑白 2维 彩色3维
        return img
    def CVToPIL(self, img):
        outimg = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGRA2RGBA))
        return outimg
    def CVToWX(self, img):
        '''    opencv 转到 wx.Image   '''
        simg = cv2.cvtColor(np.asarray(img), cv2.COLOR_BGRA2RGB)
        h, w = simg.shape[:2]
        wximage = wx.ImageFromData(w,h,simg)

        buff = cv2.cvtColor(np.asarray(img), cv2.COLOR_BGRA2RGBA)
        alphabuff = buff[:,:,3].reshape(-1)
        wximage.SetAlphaBuffer(bytearray(alphabuff))
        return wximage
    def CVShow(self, img=None, name="image"):
        cv2.namedWindow(name)  # 创建窗口并显示的是图像类型
        cv2.imshow(name, img)
        cv2.waitKey(0)  # 等待事件触发，参数0表示永久等待
        cv2.destroyAllWindows()  # 释放窗口
    def CVSave(self, img, name="cv2.png"):
        cv2.imwrite(name, img)

    # ----------PIL部分----------#
    def PILOpen(self, name):
        img = Image.open(name).convert("RGBA")
        return img
    def PILToCV(self, img):
        outimg = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
        return outimg
    def PILToWX(self, img):
        '''PIL的image转化为wxImage'''
        image = wx.EmptyImage(img.size[0], img.size[1])
        image.SetData(img.convert("RGB").tobytes())
        image.SetAlphaBuffer(img.convert("RGBA").tobytes()[3::4])
        return image
    def PILShow(self, img):
        img.show()
    def PILSave(self, img, name="pil.png"):
        img.save(name)

    # ----------WX.Image---------- #
    def WXImage(self, name):
        img = wx.Image(name)
        return img
    def WXToCV(self, img):
        resimg = np.array(img.GetData())
        Asresimg = resimg.reshape((img.GetSize()[1], img.GetSize()[0], -1))
        print("Asresimg", Asresimg.shape)

        if img.HasAlpha():
            wxAlphaStr = np.array(img.GetAlphaBuffer()).reshape((img.GetSize()[1], img.GetSize()[0], -1))
            cvimg = np.concatenate((Asresimg, wxAlphaStr),  axis=2)
            return cvimg
        return Asresimg
    def WXToPIL(self, wxImg):
        '''wxImage转化为PIL的image'''
        pilImage = Image.new('RGB', (wxImg.GetWidth(), wxImg.GetHeight()))
        pilImage.frombytes(np.array(wxImg.GetData()))
        if wxImg.HasAlpha():
            pilImage.convert('RGBA')
            wxAlphaStr = wxImg.GetAlphaBuffer()
            pilAlphaImage = Image.frombytes('L', (wxImg.GetWidth(), wxImg.GetHeight()), np.array(wxAlphaStr))
            pilImage.putalpha(pilAlphaImage)
        return pilImage
    def WXSave(self, img, name):
        img.SaveFile(name)

    # ----------制作图片文件---------- #
    def MakeImg(self, photoname, modelname, filename):
        strcmd = "img2py -n " + modelname + " -f " + photoname + " " + filename + ".py"
        os.system(strcmd)
    def MakeAddImg(self, photoname, modelname, filename):
        strcmd = "img2py -n " + modelname + " -a -f " + photoname + " " + filename + ".py"
        os.system(strcmd)

if __name__ == '__main__':
    print('Start Program...\r\n')
    photoname = "dian.png"
    simg = WImg(photoname)
    # simg.ShowChannel()
    tmp = simg.PILOpen(photoname)
    cvtmp = simg.PILToCV(tmp)
    # simg.CVShow(cvtmp)
    simg.PILSave(tmp, "pil dian.png")

    # simg.MakeImg("dian.png", "flag", "test")
    simg.MakeAddImg("dian.png", "flag2", "test")

    print('\nSuccess ...')
